﻿using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Stock.Core.MongoDB;
using System.Linq;
using System.Threading.Tasks;
using Stock.Model;
using Stock.Core.Services;
using Stock.Model.Entities;

namespace Stock.Core.Service
{
    public class OrderService:IOrderService
    {
		private readonly XTContext _context;
		private readonly IUnitOfWork _u;
        private readonly IRepository<order> _orders;

        public OrderService(IUnitOfWork u)
		{
            _u = u;
            _context = u.Context;
            _orders = u.GetRepository<order>();
		}

        public async Task<bool> insertCheck(endLog model)
        {
            var endLog = _u.GetRepository<endLog>();
            model.create_date = DateTime.Now;

            return await endLog.SaveAsync(model);
        }


        public async Task<BaseResult> insert(order model)
        {
            bool success = false;

			var _usr = new UserService(_u);
            var usr =await _usr.getUser(model.userid);
            if(usr != null)
            {
                if(usr.balance < model.moneny)
                {
                    return new BaseResult() { IsSuccess = false, Data = null, DataCount = 0, Message = "余额不足无法下单" };
                }

				await _orders.SaveAsync(model, false);

                usr.balance -= model.moneny;

                usr.freeze += model.moneny;

                await _usr.UpdateUser(usr, false);

                success = _u.Commit();
            }

            return new BaseResult(){ IsSuccess = success, Data = model.id};
		}

        public async Task<bool> Update(order order, bool tran)
		{
			var u = await _orders.UpdateAsync(order, tran);

			return u;
		}

        public async Task<List<order>> getOrders(long startTime, long endTime)
        {
            var query = from o in _context.Set<order>()
                        where o.time >= startTime && o.time <= endTime
                        orderby o.create_date descending
                        select o;

            var data = await query.ToListAsync();
            return data;
        }

        public async Task<List<order>> getMyOrders(Guid userid, long startTime, long endTime)
        {
            var query = from o in _context.Set<order>()
                        where o.time >= startTime && o.time <= endTime && o.userid == userid
                        orderby o.create_date descending
                        select o;

            var data = await query.ToListAsync();
            return data;
        }

        public async Task<List<order>> getMyUnCountOrders(Guid userid, long startTime, long endTime)
        {
            var query = from o in _context.Set<order>()
                        where o.status == 0 && o.time >= startTime && o.time < endTime && o.userid == userid
						orderby o.create_date descending
                        select o;

            var data = await query.ToListAsync();

            return data;
        }

        public async Task<List<order>> getWeekOrders(Guid? userid, DateTime startTime, DateTime endTime)
        {
            if (userid != null)
            {
				var query = from o in _context.Set<order>()
                                                  where o.create_date >= startTime && o.create_date < endTime && o.userid == userid
							orderby o.create_date descending
							select o;
				var data = await query.ToListAsync();

				return data;
            }
            else{
				var query = from o in _context.Set<order>()
							where o.create_date >= startTime && o.create_date < endTime
							orderby o.create_date descending
							select o;
				var data = await query.ToListAsync();

				return data;
            }

           
        }


		/// <summary>
		/// 获取已经结束的单子的汇总数据
		/// </summary>
		/// <returns>The order total.</returns>
		/// <param name="userid">Userid.</param>
		/// <param name="startTime">Start time.</param>
		/// <param name="endTime">End time.</param>
		public async Task<long> getOrderTotal(Guid userid, long startTime)
        {
            var query = from o in _context.Set<order>()
                        where o.time >= startTime
                    && o.userid == userid
                    && o.status == 1
                                          group o.moneny  by o.success into g
                                          select new { g.Key, moneny = g.Sum() };

            var data = await query.ToListAsync();


			var sum = data.Sum(item =>
			{
                if (item.Key == 1)
                    return 1 * item.moneny - 5;
                else if (item.Key == 2)
                    return -1 * item.moneny;
                else
                    return 0;
            });
            return sum;
        }

        public async Task<List<order>> getCurrentOrders(Guid userid)
        {
            var query = from o in _context.Set<order>()
                        where o.userid == userid && o.status == 0
						orderby o.create_date descending
						select o;

			var data = await query.ToListAsync();

			return data;
        }


		public async Task<BaseResult> getAllFinance()
		{
			var orders = await getAllUnCountOrdersSum();


            var list = await getAllUnCountOrdersGroup();

            return new BaseResult() { IsSuccess =true, Data = new {total=orders,list=list } };
		}

        /// <summary>
        /// 获取当前没结算的单子的汇总，按卖多买少汇总
        /// </summary>
        /// <returns>The all un count orders sum.</returns>
        public async Task<dynamic> getAllUnCountOrdersSum()
        {
            var query = from o in _context.Set<order>()
                        where o.status == 0
                        group o.moneny by o.type into g
                        select new { g.Key, moneny = g.Sum() };

            var data = await query.ToListAsync();
            double buy = 0;
            double sell = 0;

            if (data.Count() >= 1)
            {
                if (data[0].Key == 1)
                    buy = data[0].moneny;
                else
                    sell = data[0].moneny;
            }
            if (data.Count() >= 2)
            {
                if (data[1].Key == 1)
                    buy = data[1].moneny;
                else
                    sell = data[1].moneny;
            }
            var sum = data.Sum(item => item.moneny);
            return new { sum = sum, buy = buy, sell = sell };
        }

		/// <summary>
		/// 获取当前没结算的单子的汇总，按帐号
		/// </summary>
		/// <returns>The all un count orders sum.</returns>
		public async Task<dynamic> getAllUnCountOrdersGroup()
		{
			var query = from o in _context.Set<order>()
                        join u in _context.Set<user>() on o.userid equals u.id
						where o.status == 0
                                          group o.moneny by new { o.userid, u.name, o.type } into g
            select new { g.Key.userid, g.Key.name, g.Key.type, moneny = g.Sum() };

			var data = await query.ToListAsync();

            return data;
		}

		public async Task<List<order>> getUnCountOrders(long startTime, long endTime)
		{
			var query = from o in _context.Set<order>()
						where  o.status == 0 && o.time >= startTime && o.time < endTime
						select o;

			var data = await query.ToListAsync();

			return data;
		}

        public async Task<BaseResult> getList(DateTime starttime)
        {
            var query = from o in _context.Set<order>()
                        join u in _context.Set<user>() on o.userid equals u.id
                        where o.create_date > starttime
                        orderby o.create_date descending
                        select new { o.id, o.commission, o.count, o.create_date, o.moneny, o.stockid, u.name };

            var data = await query.ToListAsync();
            return new BaseResult() { Data = data, DataCount = query.Count(), IsSuccess = true };
        }

    }
}
